DontVoteMeDown :
Your only mistake is not in the recursion itself, but in the scope, mainly on i variable in the loop. As you didn't defined it with var or let, it was defined in the global scope, so each iteration will share it's value. What was happening is that the second iteration was changing the previous iteration value of i to 3, so it would always enter in the third level(directory1). With var or let each i will be defined in it's own scope hence it's value will be always reliable.\n\n\r\n\r\n<!DOCTYPE html>\r\n<html lang=\"en\">\r\n\r\n<head>\r\n <meta charset=\"UTF-8\">\r\n <title></title>\r\n <!-- Latest compiled and minified CSS -->\r\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\">\r\n\r\n <!-- jQuery library -->\r\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\r\n\r\n <!-- Popper JS -->\r\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"></script>\r\n\r\n <!-- Latest compiled JavaScript -->\r\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"></script>\r\n</head>\r\n\r\n<body>\r\n <script>\r\n var tree = [{\r\n 'name': 'file1',\r\n 'type': 'file',\r\n 'url': 'https://www.google.com'\r\n },\r\n {\r\n 'name': 'file2',\r\n 'type': 'file',\r\n 'url': 'https://www.google.com'\r\n },\r\n {\r\n 'name': 'file1',\r\n 'type': 'file',\r\n 'url': 'https://www.google.com'\r\n },\r\n {\r\n 'name': 'directory1',\r\n 'type': 'folder',\r\n 'url': 'https://www.google.com',\r\n 'contents': [{\r\n 'name': 'file1',\r\n 'type': 'file',\r\n 'url': 'https://www.google.com'\r\n },\r\n {\r\n 'name': 'file2',\r\n 'type': 'file',\r\n 'url': 'https://www.google.com'\r\n },\r\n ]\r\n },\r\n ]\r\n </script>\r\n\r\n <h1>Contents of \"Some\"</h1>\r\n\r\n\r\n <div id=\"tree_container\">\r\n\r\n </div>\r\n\r\n <script>\r\n var listContentsOf = function(tree, container = 'tree_container', depth = '1') {\r\n console.log(tree);\r\n console.log(container);\r\n console.log(depth);\r\n\r\n $('#' + container).append('<ul id=\"' + depth + '\"> </ul>');\r\n for (var i = 0; i < tree.length; i++) {\r\n if (tree[i].type == 'file') {\r\n $('#' + depth).append('<li>' + tree[i].name + '</li>');\r\n } else if (tree[i].type == 'folder') {\r\n $('#' + depth).append('<li>' + tree[i].name + '</li>');\r\n subID = depth + i;\r\n $('#' + depth).append('<div id=\"' + subID + 'holder\"> </div>');\r\n console.log(tree[i].contents);\r\n console.log(subID + 'holder');\r\n listContentsOf(tree[i].contents, subID + 'holder', subID);\r\n }\r\n }\r\n };\r\n\r\n listContentsOf(tree);\r\n </script>\r\n\r\n</body>\r\n<",
2019-01-31T12:03:08